package org.softmed.action.workarea;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WorkArea implements AttributerListener {

	Map<String, Object> values = new HashMap<String, Object>();

	Map<String, List<AttributerListener>> listeners = new HashMap<String, List<AttributerListener>>();

	Map<AttributerListener, List<String>> names = new HashMap<AttributerListener, List<String>>();

	public void clearListeners() {
		Collection<List<AttributerListener>> listenerList = listeners.values();
		for (List<AttributerListener> list : listenerList) {
			list.clear();
		}
		listeners.clear();

		Collection<List<String>> namesList = names.values();
		for (List<String> list2 : namesList) {
			list2.clear();
		}
		names.clear();
	}

	public WorkArea() {

	}

	public void addListener(String name, AttributerListener listener) {

		List<AttributerListener> list = listeners.get(name);
		if (list == null) {
			list = new ArrayList<AttributerListener>();

			listeners.put(name, list);
		}

		List<String> onames = names.get(listener);
		if (onames == null) {
			onames = new ArrayList<String>();

			names.put(listener, onames);
		}

		onames.add(name);
		list.add(listener);

	}

	public void removeListener(String name, AttributerListener listener) {

		List<AttributerListener> list = listeners.get(name);
		if (list != null) {
			list.remove(listener);
			if (list.size() == 0)
				listeners.remove(name);
		}

		List<String> onames = names.get(listener);
		if (onames != null) {
			onames.remove(name);
			if (onames.size() == 0)
				names.remove(listener);

		}

	}

	public void removeListener(AttributerListener listener) {
		List<String> onames = names.get(listener);
		if (onames != null) {
			List<AttributerListener> list = null;
			for (String string : onames) {
				list = listeners.get(string);
				if (list != null) {
					list.remove(listener);
					if (list.size() == 0)
						listeners.remove(string);
				}
			}

			names.remove(listener);
		}
	}

	public void setAttribute(String name, Object value) {

		values.put(name, value);

		List<AttributerListener> list = listeners.get(name);
		if (list != null)
			for (AttributerListener listener : list) {
				listener.setAttribute(name, value);
			}

	}

	public Object getAttribute(String name) {
		return values.get(name);
	}

	public void dispose() {
		values.clear();

		clearListeners();

	}

	public void clear() {
		values.clear();
	}

	public Map<String, Object> getValues() {
		return values;
	}

}
